import React, { Component, createRef } from 'react'
import { Layout, Modal, Input } from 'antd';
import { CopyOutlined, SyncOutlined } from '@ant-design/icons';
import { bindAll } from 'underscore'
const { confirm } = Modal;

const { Content } = Layout

type Props = {
  currentfile: {
    name?: string,
    value?: string
  },
  resources: string[],
  select: Function,
  add: (name: string) => void,
  changefile: (name: string) => void
}

type State = {
  visible: boolean,
  myform2: React.RefObject<Input>,
  value: string,
  types: number
}




export default class Resources extends Component<Props, State> {
  constructor(props: Props) {
    super(props)
    const { select } = props
    select()
    bindAll(this, 'addfile', 'changefile')
    this.state = {
      visible: false,
      myform2: createRef(),
      value: '',
      types: 0     // 0 不修改 1 添加 2 修改 3 删除 4 复制
    }
  }

  componentDidUpdate(_prevProps: Props, prevState: State) {
    const { value } = this.state
    const { add } = this.props
    if (value && value != prevState.value) {
      add(value)
    }
  }

  changevalue() {

  }

  addfile() {
    const thit = this
    const { visible, myform2 } = this.state
    confirm({
      title: '文件名称',
      visible,
      content: <Input type="text" ref={myform2} placeholder="请输入变量名称"  ></Input>,
      onOk(close) {
        thit.setState({
          visible: false,
          value: myform2.current?.state.value,
          types: 1
        })
        close()
      },
      okText: '确定',
      cancelText: '取消',
      onCancel() {
        thit.setState({
          visible: false,
          value: '',
          types: 0
        })
      },
      maskClosable: false
    });

  }

  keyDown(_event: React.KeyboardEvent<HTMLLIElement>) {
  }

  changefile(v: string) {

    const { currentfile, changefile } = this.props
    if (currentfile.name !== v) {
      changefile(v)
    }
  }

  render() {
    const { addfile, keyDown, changefile } = this
    const { resources, select, currentfile } = this.props
    return <Layout className="resources-view">
      <div className="resources-view-header ant-layout-header">
        <span>资源管理</span>
        <CopyOutlined title="新建文件" onClick={addfile} />
        <SyncOutlined title="刷新" onClick={() => select()} />
      </div>
      <Content className="resources-view-content">
        <ul>
          {
            resources.map((v, key) => <li className={currentfile.name == v ? 'active' : ''} onClick={() => changefile(v)} onKeyDown={keyDown} key={key}>{v+'.py'}</li>)
          }
        </ul>
      </Content>
    </Layout>
  }
}